<script setup lang="ts">
import { ref } from "vue"

const showCamera = ref(false)
const gerPermission = () => {
  showCamera.value = true

  if (!navigator.mediaDevices?.enumerateDevices) {
    console.log("enumerateDevices() not supported.")
  } else {
    // List cameras and microphones.
    navigator.mediaDevices
        .enumerateDevices()
        .then((devices) => {
          let audioSource = null
          let videoSource = null

          devices.forEach((device) => {
            if (device.kind === "audioinput") {
              audioSource = device.deviceId
            } else if (device.kind === "videoinput") {
              videoSource = device.deviceId
            }
          })
          sourceSelected(audioSource, videoSource)
        })
        .catch((err) => {
          console.error(`${err.name}: ${err.message}`)
        })
  }

  async function sourceSelected(audioSource, videoSource) {
    const constraints = {
      audio: { deviceId: audioSource },
      video: { deviceId: videoSource },
    }
    const stream = await navigator.mediaDevices.getUserMedia(constraints)
    console.log(stream)
    const video = document.querySelector("video")
    video.srcObject = stream
    video.onloadedmetadata = () => {
      video.play()
    }
  }
}
const closeCamera = () => { showCamera.value = false }

</script>

<template>
  <div class="w-80 h-80 flex justify-center items-center relative">
    <video width="320" height="320" v-if="showCamera"></video>
    <button type="button" @click="gerPermission" v-else>允许摄像头</button>
    <button type="button" class="absolute bottom-0" v-if="showCamera" @click="closeCamera">销毁摄像头</button>
  </div>
</template>

<style scoped lang="scss">

</style>
